import { getCurrentInstance, onMounted, onUnmounted, ref } from 'vue'
import { get } from '@/utils'

/**
 *@desc 监听消息回调执行对地图进行打点  （实验性暂时不用)
 *@author     邓清波
 *@param  socketInstance  {Object} scoket实例
 *@param  that  {Object} vue实例上下文 (map组件使用的是vue2的写法 无法使用getCurrentInstance)
 *
 * **/
function useObserverScoket(socketInstance, that) {
  console.log('socketInstance', socketInstance)
  if (!socketInstance) throw new Error('socketInstance as null ')

  console.log('that', that)
  const markerInstance = {} // 事件点位实例

  /**
   * @desc  创建点位并打点设置中心点
   *
   * **/
  function createGlMarker(eventDetail) {
    // [key] 事件类型 :value '事件icon名'
    // 映射事件类型icon
    const mapperGlEventIcon = {
      1: 'gl-sgzh',
      2: 'gl-eltq',
      3: 'gl-dzzh',
      4: 'gl-tfqt',
      5: 'gl-sgyh',
      6: 'gl-zdhd',
      7: 'gl-jhqt'
    }
    const path = []
    const lon = get(eventDetail, 'eventPositionList.0.eventLon')
    const lat = get(eventDetail, 'eventPositionList.0.eventLat')
    const eventRoadId = get(eventDetail, 'eventPositionList.0.eventRoadId', '')
    const eventStartMileageK = get(eventDetail, 'eventPositionList.0.eventStartMileageK', '') // 千米桩号
    const eventStartMileageM = get(eventDetail, 'eventPositionList.0.eventStartMileageM', '') // 百米桩
    const text = `${eventRoadId} K${eventStartMileageK}+${eventStartMileageM}`

    lon && path.push(lon)
    lat && path.push(lat)

    if (path.length !== 2) return
    that.$mapSdk().setMapCenter(path)

    // 打点信息
    const points = [
      {
        icon: mapperGlEventIcon[eventDetail.eventType],
        path: path,
        name: text,
        size: [38, 44]
      }
    ]
    markerInstance.value && that.removeMarker()
    markerInstance.value = that.$mapSdk().createMvMapMarkerLayer(points, {}, (e, data) => {})
  }
  /**
   * @desc  销毁点位
   *
   * **/
  function removeMarker() {
    markerInstance.value = that.$mapSdk().removeMvMapMarkerLayer(markerInstance.value)
  }

  //  监听消息
  socketInstance.stompClient.subscribe('/user/queue/talk/event/demo', function (res) {
    console.log('/user/queue/talk/event/demo', '----res:')
    const body = JSON.parse(res.body)
    console.log('eventDetail', body)
    if (body.content) {
      createGlMarker(body.content)
    } else {
      removeMarker()
    }
  })

  onUnmounted(() => removeMarker())
}

export default useObserverScoket
